import request from '@/dvadmin/request/index.js'
import Env from '@/env.js'
const accountInfo = uni.getAccountInfoSync();
const state = {
	// 小程序 appId
	appId: accountInfo.miniProgram.appId,
    // 品牌商ID
    tenantId: uni.getStorageSync("tenantId"),
    // 品牌商domain
    tenantDomain: uni.getStorageSync("tenantDomain"),
    // 品牌商名称
    tenantTitle: uni.getStorageSync("tenantTitle") || "请选择品牌商",
    // 品牌商logo
    tenantSrc: uni.getStorageSync("tenantSrc") || '/static/logo.png',
}
const mutations = {
	// 保存token
	setToken(state, token) {
		// 保存token
		state.accessToken = token
		uni.setStorageSync('accessToken', token);
	},
	// 登录信息保存
	setUserInfo(state, data) {
		state.userInfo = data;
		uni.setStorageSync('userInfo', data);
	},
	// 设置租户信息
	setTenantInfo(state, tenant) {
		uni.setStorageSync("tenantId", tenant.id)
		if (tenant.domain) {
			uni.setStorageSync("tenantDomain", tenant.domain)
		}
		uni.setStorageSync("tenantTitle", tenant.name)
		uni.setStorageSync("tenantSrc", tenant.logo_img || '/static/logo.png')
		state.tenantId = tenant.id
		state.tenantDomain = tenant.domain
		state.tenantTitle = tenant.name
		state.tenantSrc = tenant.logo_img || '/static/logo.png'
	},
}
const getters = {}
const actions = {
	// 获取用户信息
	async getUserInfo({
		commit,
		dispatch,
		getters,
		state
	}) {
		return new Promise((resolve, reject) => {
			// if (state.userInfo && state.userInfo.id !== '') return
			request({
			    url: '/api/uniapp/user_info/get_user_info/',
			    method: 'get'
			}).then(async res => {
				await commit('setUserInfo', res.data)
				if (Env.MODE !== 'saas') {
					await commit('setTenantInfo', {
						id: res.data.tenant_id,
						name: res.data.tenant_name
					})
				}
				resolve(res.data)
			}).catch(async err => {
				reject(err)
			})
		})
	},
	// 获取token
	async getToken({
		state,
		dispatch
	}, data) {
		return new Promise(async (resolve, reject) => {
			uni.login({
				provider: 'weixin',
				success: (res) => {
					//调用微信登录接口
					request({
						url: '/api/uniapp/wxlogin/',
						method: 'post',
						data: {
							username: 'username',
							password: res.code,
							phone_code: data.phoneCode,
							mode: Env.MODE,
							app_id: state.appId,
							login_type: 'we_chat',
						},
						custom: {
							auth: false
						}
					}).then(res => {
						if (res.data.token) {
							// 保存token
							this.commit('setToken', res.data.token)
							resolve(res.data)
						} else {
							reject(err)
						}
						uni.hideLoading();
					}).catch(err => {
						console.log(err)
						reject(err)
						uni.hideLoading();
					})
				}
			})
		})
	},
}

export default {
	actions,
	state,
	mutations,
	getters
}
